package questions;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁，循环等待锁，不阻塞当前线程，一直在执行循环
 */
public class SpinLock {
    private AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + " 开始拿锁！");
        //当且仅当原子引用中的值被更新为当前线程，说明当前线程占有了锁。退出循环
        while (!atomicReference.compareAndSet(null, thread)) {
        }
        System.out.println(thread.getName() + " 获得了锁！");
    }
    public void unLock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(thread.getName()+" 释放了锁！");
    }

    public static void main(String[] args) throws InterruptedException {
        SpinLock spinLock = new SpinLock();
        new Thread(()->{
            spinLock.lock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
            }
            System.out.println(Thread.currentThread().getName() + "执行完毕");
            spinLock.unLock();
        },"t1").start();
        TimeUnit.SECONDS.sleep(1);
        new Thread(()->{
            spinLock.lock();
            System.out.println(Thread.currentThread().getName() + "执行中");
            spinLock.unLock();
            System.out.println(Thread.currentThread().getName() + "执行完毕");
        },"t2").start();

    }




}
